//
//  Badge.swift
//  Social
//
//  Created by 李响 on 2019/3/19.
//  Copyright © 2019 shengsheng. All rights reserved.
//

import Foundation

struct BadgeWrapper<Base> {
    fileprivate let base: Base
    init(_ base: Base) {
        self.base = base
    }
}

protocol BadgeCompatible {
    associatedtype BadgeCompatibleType
    var badge: BadgeCompatibleType { get }
}

extension BadgeCompatible {
    
    var badge: BadgeWrapper<Self> {
        get { return BadgeWrapper(self) }
    }
}

extension UIView: BadgeCompatible { }

extension BadgeWrapper where Base: UIView {
    
    private var view: BadgeView {
        if let view = base.viewWithTag(10001) as? BadgeView {
            return view
        }
        let view = BadgeView(frame: base.bounds)
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.tag = 10001
        base.addSubview(view)
        return view
    }
    
    /// 设置文本
    ///
    /// - Parameter text: 文本
    @discardableResult
    func set(text: String?) -> BadgeWrapper {
        guard let text = text, !text.isEmpty else {
            view.isHidden = true
            return self
        }
        view.isHidden = false
        base.bringSubviewToFront(view)
        view.set(text: text)
        return self
    }
    
    /// 设置字体
    ///
    /// - Parameter font: 字体
    @discardableResult
    func set(font: UIFont) -> BadgeWrapper {
        view.set(font: font)
        return self
    }
    
    /// 设置位置偏移
    ///
    /// - Parameter offset: 偏移
    @discardableResult
    func set(offset: CGPoint) -> BadgeWrapper {
        view.offset = offset
        return self
    }
    
    /// 设置边距比例 (默认为字号0.4倍)
    ///
    /// - Parameter margin: 边距
    @discardableResult
    func set(margin: CGFloat) -> BadgeWrapper {
        view.margin = margin
        return self
    }
    
    /// 设置颜色 (默认为 red)
    ///
    /// - Parameter color: 颜色
    @discardableResult
    func set(color: UIColor) -> BadgeWrapper {
        view.color = color
        return self
    }
}
